package com.topfinance.cnaps2.web.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.topfinance.cnaps2.ebo.SysUserEbo;
import com.topfinance.cnaps2.util.Constants;

public class AuthFilter implements Filter {

	private static Log log = LogFactory.getLog(AuthFilter.class);
	protected FilterConfig filterConfig = null;

	protected ServletContext context = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.context = filterConfig.getServletContext();
		//log.debug("AuthFilter init successfully!");
	}

	public void destroy() {
		//log.debug("AuthFilter destroy!");
		this.filterConfig = null;
		this.context = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//log.debug("[AuthFilter doFilter!]");
		if (!(request instanceof HttpServletRequest)) {
			log.error("Can only process HttpServletRequest. Client request is "
					+ request.getClass().getName() + "Client is from "
					+ request.getRemoteAddr() + ":" + request.getRemotePort());
			throw new ServletException("Can only process HttpServletRequest");
		}

		if (!(response instanceof HttpServletResponse)) {
			log.error("Can only process HttpServletResponse. Client request is "
							+ request.getClass().getName()
							+ "Client is from "
							+ request.getRemoteAddr()
							+ ":"
							+ request.getRemotePort());
			throw new ServletException("Can only process HttpServletResponse");
		}
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//log.debug("req.getServletPath():"+req.getServletPath());
		//log.debug("req.getQueryString():"+req.getQueryString());
		
		try {
			doFilterCb(req, resp, chain);
		} catch (Exception e) {
			log.error("doFilter() - " + e.getMessage(), e);
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}

	public void doFilterCb(HttpServletRequest req, HttpServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		String uri = getURI(req);
		try {
			// is login action
			if (uri.indexOf("/loginAction.action") > -1||(uri.indexOf("/home.action") > -1)) {
				//if(req.getHeader("Referer")!=null && req.getHeader("Referer").indexOf("forward_") > -1)
				//	req.setAttribute("forwardurl",  req.getHeader("Referer"));
				chain.doFilter(req, res);
				return;
			}else if(uri.indexOf(".action") == -1){
				chain.doFilter(req, res);
				return;
			}
			
			// just check if user can access the specified URL
			if (!checkIfValidSysUserEboSession(req, res)) {
				chain.doFilter(req, res);
				return;
			}
			chain.doFilter(req, res);
		} catch (Exception e) {
			log.error("doFilterCb() - " + e.getMessage(), e);
			res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}

	private boolean checkIfValidSysUserEboSession(HttpServletRequest req,
			HttpServletResponse res) throws ServletException, IOException {
		String forwardUrl = "";
		//log.debug("[AuthFilter Here]" + req.getSession().getAttribute(Constants.SESSION_USER_EBO));
		if (req.getSession().getAttribute(Constants.SESSION_USER_EBO) == null) {
			//log.debug("[AuthFilter NULL Here]");
//			if (getURI(req).indexOf("/siteadmin/") > -1) {
//				forwardUrl ="/siteadmin/loginAction.do?method=preLogin";
//			} else if (getURI(req).indexOf("/usercenter/") > -1) {
//				forwardUrl = "/usercenter/loginAction.do?method=preLogin";
//				if(req.getHeader("Referer")!=null && req.getHeader("Referer").indexOf("forward_") > -1)
//					req.setAttribute("forwardurl",  req.getHeader("Referer"));
//			} else {
//				forwardUrl = req.getContextPath() + "/commons/404.jsp";
//			}
			forwardUrl = req.getContextPath() + "/jsp/home.jsp";
			log.debug("[AuthFilter forwardUrl]" + forwardUrl);
			req.getRequestDispatcher(forwardUrl).forward(req, res);
			return false;
		} else {
			// just check if user can access the specified URL
			SysUserEbo userEbo = (SysUserEbo) req.getSession().getAttribute(Constants.SESSION_USER_EBO);
			return true;
		}
	}

//	private boolean checkAuthorization(HttpServletRequest req) {
//		SysUserEbo userEbo = (SysUserEbo) req.getSession().getAttribute(
//				Constants.SESSION_USER_EBO);
//		log.debug("req.getServletPath():"+req.getServletPath());
//		log.debug("req.getQueryString():"+req.getQueryString());
//		return PowersManager.checkAuthorization(req.getServletPath(), req
//				.getQueryString(), userEbo.getSysUserEboOperationCodes());
//
//	}
//
	public static String getURI(HttpServletRequest request) {
		String uri = request.getRequestURI();
		log.debug("[AuthFilter URI]" + uri);
		int pathParamIndex = uri.indexOf('?');
		int ctxLength = request.getContextPath().length();
		if (pathParamIndex > 0) {
			// strip everything after the first semi-colon
			uri = uri.substring(ctxLength, pathParamIndex);
		} else {
			uri = uri.substring(ctxLength);
		}
		return uri;
	}

}
